package com.yanhui.utils.file;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

public class _fileUtils{
    public static void main(String[] args) throws Exception {
//        String path = "D:\\test";
//        String[] files = {"a","b","c"};
//        String suffixName = "(艳辉网)";
//        _fileUtils.multiFloder(path, files , suffixName );
//
//        _fileUtils replacementChain = new _fileUtils();
//        replacementChain.addRegulation(".mp4", "(艳辉网分享福利的网站).mp4");
//        _fileUtils.multiRename("D:\\test\\1-a(艳辉网)", replacementChain);


        //将C:\Users\admin\Desktop\createCode\com\yanhui下所有文件中的yanhui改为lwx
        changeText("C:\\Users\\admin\\Desktop\\createCode\\com\\yanhui","yanhui","lwx");
//        changeSpaceText("C:\\Users\\admin\\Desktop\\getAddressByIp.jsp",">\\s+<","><");

    }

    public static void changeSpaceText(String filename, String oldStr, String newStr) throws Exception {
        System.out.println("读取、修改"+filename+"文件");
        String content = _txtUtils.readTxtFile(filename);
        content = content.replaceAll(oldStr, newStr);
        _txtUtils.writeFileForContent(content, filename);
    }

    public static void changeText(String path, String oldStr, String newStr) throws Exception {
        File file = new File(path);
        boolean isDirectory = file.isDirectory();
        if(!isDirectory){
            System.out.println(path+"不是一个文件夹！");
            return;
        }
        String[] files = file.list();
        File f = null;
        String filename = "";

        for(int i = 0; i<files.length;i++){
            filename = files[i];
            f = new File(path+"\\"+filename);
            boolean isDirectory2 = f.isDirectory();
            if(!isDirectory2){
                //读取文件 修改文件
                System.out.println("读取、修改"+filename+"文件");
                String content = _txtUtils.readTxtFile(path+"\\"+filename);
                content = content.replaceAll(oldStr, newStr);
                _txtUtils.writeFileForContent(content, path+"\\"+filename);
            }else{
                changeText(path+"\\"+filename,oldStr,newStr);
            }

            System.out.println("批量修改"+path+"成功！");
        }
    }

    private Map map;
    public _fileUtils(){
        this.map=new HashMap();
    }
    public Map getMap() {
        return map;
    }

    @SuppressWarnings("unchecked")
    public _fileUtils addRegulation(String oldStr, String newStr){
        this.map.put(oldStr, newStr);
        return this;
    }

    public static void multiFloder(String path, String[] files, String suffixName){
        String filename = "";
        for(int i = 0; i<files.length;i++){
            filename = (i+1)+"-"+files[i];
            File f = new File(path+"\\"+filename+suffixName);
            f.mkdirs();
            System.out.println("创建文件夹成功！");
        }
    }

    public static void multiRename(String path, _fileUtils replacementChain){
        File file = new File(path);
        boolean isDirectory = file.isDirectory();
        if(!isDirectory){
            System.out.println(path+"不是一个文件夹！");
            return;
        }
        String[] files = file.list();
        File f = null;
        String filename = "";
        String oldFileName = "";

        for(int i = 0; i<files.length;i++){
            oldFileName = files[i];
            filename = files[i];
            Map map = replacementChain.getMap();
            Iterator it = map.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry entry = (Map.Entry) it.next();
                filename = filename.replace((String)entry.getKey(), (String)entry.getValue());
            }
            filename = (i+1)+"-"+filename;
            f = new File(path+"\\"+oldFileName);
            f.renameTo(new File(path+"\\"+filename));
            System.out.println("批量修改"+filename+"成功！");
        }
    }


    /**
     * 指定每一份文件的边界写入不同的文件中
     * @param file 源文件
     * @param index 文件顺序标识
     * @param begin 开始指针的位置
     * @param end 结束指针的位置
     * @return long 文件指针
     */
    public static long getWrite(String file, int index, long begin, long end){

        long endPointer = 0L;

        try {
            //声明切割文件磁盘空间
            RandomAccessFile in = new RandomAccessFile(new File(file), "r");
            //定义一个可读可写并且后缀名为.tmp二进制的临时文件
            RandomAccessFile out = new RandomAccessFile(file+"_"+index+".tmp", "rw");
            //声明具体每一个文件字节数组为1024
            byte[] b = new byte[1024];
            //从指定文件读取字节流
            in.seek(begin);
            int n = 0;
            while (in.getFilePointer() <= end && (n =in.read(b)) != -1) {
                out.write(b, 0, n);  //写入不同的二进制文件
            }

            //定义当前读取文件指针
            endPointer = in.getFilePointer();
            //关闭输入流
            in.close();
            //关闭输出流
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return endPointer;
    }

    /**
     * 文件切片
     * @param file 需要被切割的源文件
     * @param count 切割文件的个数
     */
    public static void getSplitFile(String file, int count){
        try {
            //预分配文件占用磁盘空间“r”表示只读的方式“rw”支持文件随机读取和写入
            RandomAccessFile raf = new RandomAccessFile(new File(file), "r");
            //文件长度
            long length = raf.length();
            //计算切片后，每一文件的大小
            System.out.println(length);
            long maxSize = length / count;
            //定义初始文件偏移量（读取文件进度）
            long offset = 0L;
            //开始切割
            for(int i = 0; i < count-1; i++){ //count-1 其中的一份文件不处理
                //初始化
                long fbegin = offset;
                //分割第几份文件
                long fend = (i+1) * maxSize;
                //写入二进制临时文件中
                offset = getWrite(file, i, fbegin, fend);
            }

            //将剩余的写入到最后一份文件中
            if((int)(length - offset) > 0){
                getWrite(file, count-1, offset, length);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        String file = "D:/a.mkv";
//        int count = 8;
//        int temCount = count;
//        String tempFile = file;
//        //		getSplitFile(file, count );
//        merge(file, tempFile, temCount);
//    }

    /**
     * 合并文件
     * @param file 指定合并后的文件
     * @param tempFile 分割前的文件名
     * @param temCount 文件的个数
     */
    public static void merge(String file, String tempFile, int temCount){
        RandomAccessFile raf = null;
        try {
            // 声明随机可读可写的文件
            raf = new RandomAccessFile(new File(file), "rw");
            // 开始合并文件，对应切片的二进制文件
            for(int i = 0; i < temCount; i++){
                RandomAccessFile reader = new RandomAccessFile(
                        new File(tempFile+"_"+i+".tmp"), "r");
                byte[] b = new byte[1024];
                int n = 0;
                while((n = reader.read(b)) != -1){
                    raf.write(b, 0, n);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 读取文件夹下的所有文件的内容
     * @param path
     */
    public static void readFilesDir(String path){
        LinkedList<File> list = new LinkedList<File>();
        File dir = new File(path);
        File[] files = dir.listFiles();

        for(File file : files){
            if(file.isDirectory()){
                list.add(file);
                System.out.println(file.getAbsolutePath());
            }else{
                //处理文件内容
                System.out.println(file.getAbsolutePath());
            }
        }

        File temp;
        while(!list.isEmpty()){
            temp = list.removeFirst();
            if(temp.isDirectory()){
                files = temp.listFiles();
                if(files == null) continue;
                for(File file : files){
                    if(file.isDirectory()){
                        list.add(file);
                    }else{
                        //处理文件内容
                        System.out.println(file.getAbsolutePath());
                    }
                }
            }else{
                //处理文件内容,这种情况好像不会发生
                System.out.println("-------------");
            }
        }
    }

    /**
     * 读取单个文件的内容
     * @param file
     * @return 文件的内容，String
     */
    public static String readContents(File file){
        StringBuilder res = new StringBuilder();
        BufferedReader br = null;

        try {
            br = new BufferedReader(new FileReader(file));
            while(br.ready()){
                res.append(br.readLine() + "\n");
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return res.toString();
    }

    /**
     * 保存文件
     */
    public static void saveFiles(String contents, String output){
        File outputFile = new File(output);
        try {
            if(!outputFile.exists()){
                outputFile.createNewFile();
            }

            BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile, true));
            bw.write(contents);

            bw.flush();
            bw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("保存成功！！！");
    }

//    public static void main(String[] args) {
//        String path = "F:/testfile";
//
//        readFilesDir(path);
//
//    }
}